#!/usr/bin/python
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import matplotlib.dates as md
import sqlite3 as sdb
import numpy as np
import datetime as dt
import os

def plot(variables,values):
	val_array = np.array(values)
	plt.subplots_adjust(bottom=0.3)
	plt.xticks( rotation=90 )
	ax1=plt.gca()
		
	timestamps = val_array[:,0]
	dates = []
	for i in timestamps:
		dates.append(dt.datetime.fromtimestamp(i))

	plot_vars = [1,8,10,7];
	for i in plot_vars:
		ax1.plot(	
			list(dates), val_array[:,i], label=variables[i][0]
			)
	ax1.legend()
	
	ax2 = ax1.twinx()
	ax2.plot(list(dates), val_array[:,8], 'y')
	
	xfmt = md.DateFormatter('%y/%m/%d %H:%M')
	ax2.xaxis.set_major_formatter(xfmt)
	
	ax1.grid(True)
	plt.show()

import time
db_path = '/home/tom/logs/'
db_filename = time.strftime('sunsaver_%Y_07.sdb')

db_file = db_path + db_filename

exists = os.path.isfile(db_file)

if not exists:
	print "Database file not found!"
	exit(1)

conn = sdb.connect(db_file)
curs = conn.cursor()
curs.execute("select * from archive")

variables =	[
		['dateTime','s'], 	# 0
		['adc_vb_f','V'], 	# 1
		['adc_va_f','V'], 	# 2
		['adc_vl_f','V'], 	# 3
		['adc_ic_f','A'], 	# 4
		['adc_il_f','A'], 	# 5
		['T_hs','C'], 		# 6
		['charge_state',''],# 7 
		['Power_out','W'], 	# 8
		['Ahc_daily','Ah'],	# 9 
		['Ahl_daily','Ah'],	# 10
		['load_power','W']	# 11
		]

	#0 START
	#1 NIGHT_CHECK
	#2 DISCONNECT
	#3 NIGHT
	#4 FAULT
	#5 BULK_CHARGE
	#6 ABSORPTION
	#7 FLOAT
	#8 EQUALIZE

	# State		Voltage
   #100.00000    25.40000
    #90.00000    25.00000
    #80.00000    24.84000
    #70.00000    24.64000
    #60.00000    24.40000
    #50.00000    24.12000
    #40.00000    23.80000
    #30.00000    23.50000
    #20.00000    23.16000
    #10.00000    22.62000
     #0.00000    21.00000

values = []

start = 1

for rows in curs:
	vals_tmp = list(rows)
	vals_tmp.append(vals_tmp[3]*vals_tmp[5])
	if start:
	  prev_time = vals_tmp[0]
	  start = 0
	  
	#print prev_time, " ", vals_tmp[0]
	if ((vals_tmp[0]-prev_time) > 2000):
	  dud = [float('NaN')] * 12
	  dud[0] = prev_time + 2
	  #print "Vals temp: ",vals_tmp
	  #print "Dud entry: ",dud
	  values.append( dud )
	  
	prev_time = vals_tmp[0]
	values.append(vals_tmp)
	
	
#print variables
#print values
plot(variables,values)
